<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import DefaultLayout from '@/components/layout/DefaultLayout.vue'
import { useBlogStore } from '@/store/blog'

const route = useRoute()
const router = useRouter()
const blogStore = useBlogStore()

const blogs = computed(() => {
  return blogStore.blogs.map(blog => ({
    ...blog,
    typeName: blog.blogType?.typeName || '未分类',
    authorName: blog.user?.name || '未知作者'
  }))
})
const totalPages = computed(() => blogStore.totalPages)
const currentPage = ref(1)
const pageSize = ref(12)
const loading = ref(true)
const searchQuery = ref('')
const selectedType = ref(null)
const blogTypes = ref([])

// 从URL参数获取初始值
onMounted(async () => {
  if (route.query.type) {
    selectedType.value = parseInt(route.query.type)
  }
  
  if (route.query.page) {
    currentPage.value = parseInt(route.query.page)
  }
  
  if (route.query.query) {
    searchQuery.value = route.query.query
  }
  
  try {
    const typeData = await blogStore.fetchBlogTypes()
    blogTypes.value = typeData
    
    await fetchBlogs()
  } catch (error) {
    console.error('Error loading blogs:', error)
  } finally {
    loading.value = false
  }
})

// 监听URL参数变化
watch(() => route.query, (newQuery) => {
  if (newQuery.type && newQuery.type !== selectedType.value) {
    selectedType.value = parseInt(newQuery.type)
    fetchBlogs()
  }
  
  if (newQuery.page && parseInt(newQuery.page) !== currentPage.value) {
    currentPage.value = parseInt(newQuery.page)
    fetchBlogs()
  }
}, { deep: true })

const fetchBlogs = async () => {
  loading.value = true
  try {
    if (selectedType.value) {
      await blogStore.fetchBlogsByType(selectedType.value, currentPage.value, pageSize.value)
    } else {
      await blogStore.fetchBlogs(currentPage.value, pageSize.value, searchQuery.value)
    }
  } catch (error) {
    console.error('Error loading blogs:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  updateUrlParams()
  fetchBlogs()
}

const handlePageChange = (page) => {
  currentPage.value = page
  updateUrlParams()
  fetchBlogs()
  // 滚动到顶部
  window.scrollTo(0, 0)
}

const selectType = (typeId) => {
  if (selectedType.value === typeId) {
    selectedType.value = null
  } else {
    selectedType.value = typeId
  }
  currentPage.value = 1
  updateUrlParams()
  fetchBlogs()
}

const updateUrlParams = () => {
  const query = {}
  
  if (selectedType.value) {
    query.type = selectedType.value
  }
  
  if (currentPage.value > 1) {
    query.page = currentPage.value
  }
  
  if (searchQuery.value) {
    query.query = searchQuery.value
  }
  
  router.push({ path: '/blogs', query })
}

const goToBlogDetail = (id) => {
  router.push(`/blogs/${id}`)
}

const getTypeNameById = (typeId) => {
  const type = blogTypes.value.find(t => t.id === typeId)
  return type ? type.name : '未分类'
}
</script>

<template>
  <DefaultLayout>
    <div class="blogs-page">
      <!-- 页面标题和搜索 -->
      <div class="blogs-header">
        <h1 class="page-title">所有博客</h1>
        <div class="search-box">
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="搜索博客..." 
            class="search-input"
            @keyup.enter="handleSearch"
          />
          <button class="search-btn" @click="handleSearch">
            搜索
          </button>
        </div>
      </div>
      
      <!-- 分类过滤器 -->
      <div class="blog-filters">
        <div class="filter-label">按分类筛选:</div>
        <div class="filter-tags">
          <button 
            class="filter-tag" 
            :class="{ active: !selectedType }"
            @click="selectType(null)"
          >
            全部
          </button>
          <button 
            v-for="type in blogTypes" 
            :key="type.typeId"
            class="filter-tag"
            :class="{ active: selectedType === type.typeId }"
            @click="selectType(type.typeId)"
          >
            <div class="filter-tag-content">
              <span class="tag-name">{{ type.typeName }}</span>
              <div class="tag-info">
                <span class="tag-author">{{ type.user?.name || '未知' }}</span>
                <span class="tag-count">{{ type.blogCount || 0 }}篇</span>
              </div>
            </div>
          </button>
        </div>
      </div>
      
      <!-- 博客列表 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
      </div>
      
      <div v-else-if="blogs.length === 0" class="empty-state">
        <div class="empty-icon">📝</div>
        <h3>没有找到相关博客</h3>
        <p>尝试其他搜索条件或浏览所有博客</p>
        <button class="btn btn-primary" @click="selectType(null); searchQuery = ''; fetchBlogs()">
          浏览所有博客
        </button>
      </div>
      
      <div v-else class="blogs-grid">
        <div 
          v-for="blog in blogs" 
          :key="blog.blogId" 
          class="blog-card"
          @click="goToBlogDetail(blog.blogId)"
        >
          <div class="blog-image" :style="blog.coverImage ? `background-image: url(${blog.coverImage})` : ''">
            <span v-if="!blog.coverImage" class="no-image">博客</span>
          </div>
          <div class="blog-content">
            <div class="blog-meta">
              <span class="blog-type">{{ blog.typeName }}</span>
              <span class="blog-date">{{ new Date(blog.createTime).toLocaleDateString() }}</span>
            </div>
            <h3 class="blog-title">{{ blog.title }}</h3>
            <p class="blog-summary">{{ blog.summary || (blog.content ? blog.content.replace(/<[^>]+>/g, '').substring(0, 120) + '...' : '') }}</p>
            <div class="blog-footer">
              <div class="blog-author">{{ blog.authorName }}</div>
              <div class="blog-stats">
                <span class="blog-views">{{ blog.views || 0 }} 阅读</span>
                <span class="blog-likes">{{ blog.likes || 0 }} 赞</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="totalPages > 1" class="pagination">
        <button 
          class="pagination-btn" 
          :disabled="currentPage === 1"
          @click="handlePageChange(currentPage - 1)"
        >
          上一页
        </button>
        
        <button 
          v-for="page in totalPages" 
          :key="page"
          class="pagination-btn"
          :class="{ active: currentPage === page }"
          @click="handlePageChange(page)"
        >
          {{ page }}
        </button>
        
        <button 
          class="pagination-btn" 
          :disabled="currentPage === totalPages"
          @click="handlePageChange(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>
  </DefaultLayout>
</template>

<style>
.blogs-page {
  padding: 1rem 0 3rem;
}

.blogs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.page-title {
  font-size: 2rem;
  font-weight: 600;
  margin: 0;
}

.search-box {
  display: flex;
  width: 100%;
  max-width: 400px;
}

.search-input {
  flex: 1;
  padding: 0.6rem 1rem;
  border: 1px solid var(--border-color);
  border-radius: 4px 0 0 4px;
  font-size: 0.95rem;
}

.search-btn {
  padding: 0 1.5rem;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  font-weight: 500;
}

.search-btn:hover {
  background-color: #3a5982;
}

.blog-filters {
  margin: 2rem 0;
  padding: 1.5rem;
  background: var(--filter-bg, #f8f9fa);
  border-radius: 12px;
  border: 1px solid var(--border-color, #eaeaea);
}

.filter-label {
  font-weight: 500;
  margin-bottom: 1rem;
  color: var(--text-secondary, #666);
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.filter-tag {
  background: var(--tag-bg, #ffffff);
  border: 1px solid var(--border-color, #eaeaea);
  border-radius: 8px;
  padding: 0.75rem 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  color: var(--text-primary, #2c3e50);
  font-size: 0.95rem;
  min-width: 120px;
}

.filter-tag:hover {
  border-color: var(--primary-color, #4a6fa5);
  transform: translateY(-2px);
}

.filter-tag.active {
  background: var(--primary-color, #4a6fa5);
  color: white;
  border-color: var(--primary-color, #4a6fa5);
}

.filter-tag-content {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.tag-name {
  font-weight: 500;
}

.tag-info {
  display: flex;
  gap: 0.5rem;
  font-size: 0.85rem;
  color: var(--text-light, #999);
}

.tag-author {
  color: var(--primary-color, #4a6fa5);
}

.tag-count {
  background: var(--count-bg, #f0f2f5);
  padding: 0.1rem 0.5rem;
  border-radius: 10px;
  font-size: 0.8rem;
}

.filter-tag.active .tag-info {
  color: rgba(255, 255, 255, 0.9);
}

.filter-tag.active .tag-count {
  background: rgba(255, 255, 255, 0.2);
  color: white;
}

.blogs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
}

.blog-card {
  border-radius: 8px;
  overflow: hidden;
  background: white;
  box-shadow: var(--card-shadow);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.blog-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.blog-image {
  height: 180px;
  background-color: var(--background-dark);
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-image {
  color: white;
  font-size: 1.5rem;
  font-weight: 500;
}

.blog-content {
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.blog-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1rem;
  font-size: 0.875rem;
}

.blog-type {
  color: var(--primary-color);
  font-weight: 600;
}

.blog-date {
  color: var(--text-light);
}

.blog-title {
  font-size: 1.25rem;
  margin-bottom: 0.75rem;
  line-height: 1.4;
}

.blog-summary {
  font-size: 0.95rem;
  line-height: 1.6;
  color: var(--text-light);
  margin-bottom: 1.5rem;
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.blog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

.blog-author {
  font-weight: 500;
}

.blog-stats {
  display: flex;
  gap: 1rem;
  color: var(--text-light);
  font-size: 0.875rem;
}

.empty-state {
  text-align: center;
  padding: 3rem 0;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.empty-state h3 {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
}

.empty-state p {
  color: var(--text-light);
  margin-bottom: 1.5rem;
}

.pagination {
  display: flex;
  justify-content: center;
  gap: 0.5rem;
}

.pagination-btn {
  padding: 0.5rem 1rem;
  border: 1px solid var(--border-color);
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
}

.pagination-btn:hover:not(:disabled) {
  border-color: var(--primary-color);
  color: var(--primary-color);
}

.pagination-btn.active {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 3rem 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(74, 111, 165, 0.2);
  border-radius: 50%;
  border-top-color: var(--primary-color);
  animation: spin 1s linear infinite;
}

@keyframes spin {
  100% {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .blogs-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-box {
    max-width: 100%;
  }
  
  .blogs-grid {
    grid-template-columns: 1fr;
  }
  
  .blog-filters {
    padding: 1rem;
    margin: 1rem 0;
  }
  
  .filter-tags {
    gap: 0.75rem;
  }
  
  .filter-tag {
    padding: 0.5rem 0.75rem;
    min-width: auto;
    flex: 1;
  }
}

/* 暗黑模式 */
@media (prefers-color-scheme: dark) {
  .blog-filters {
    --filter-bg: #1a1a1a;
    --border-color: #333;
    --text-primary: #e1e1e1;
    --text-secondary: #999;
    --tag-bg: #2a2a2a;
    --count-bg: #333;
  }
}
</style> 